//
//  PeriodOfTimeDataVC.m
//  RTUApp
//
//  Created by 陈德军 on 2017/5/18.
//  Copyright © 2017年 陈德军. All rights reserved.
//时段数据

#import "PeriodOfTimeDataVC.h"
#import "EssentialParameterTableViewCell.h"
#import "KSDatePicker.h"
#import "SearchEquipmentVC.h"

@interface PeriodOfTimeDataVC ()<UITableViewDelegate,UITableViewDataSource>{
    //起始日期
    UILabel *starDateDetailLabel;
    NSDate *starDateDetail;
    //结束日期
    UILabel *stopDateDetailLabel;
    //起始时间
    UILabel *starTimeDetailLabel;
    //结束时间
    UILabel *stopTimeDetailLabel;
    
    
    int h;
    NSString *str6;
    NSString *strCopy;
}
/**
 *  table
 */
@property (nonatomic,strong) UITableView *tableV;
/**
 *  数据数组
 */
@property (nonatomic,strong) NSMutableArray<SearchEquipmentModel *> *dataSoucer;
@end

@implementation PeriodOfTimeDataVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"蓝牙连接断开";
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataSoucer = [NSMutableArray new];
    strCopy = @"1234";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    starDateDetail = [dateFormatter dateFromString:[self getCurrentDate]];
    SearchEquipmentModel *model = [SearchEquipmentModel new];
    model.num = @"序号";
    model.name = @"日期/时段";
    model.macID = @"埋深(米)";
    model.butTitle = @"水温(°C)";
    [self.dataSoucer addObject:model];
    [self addTableView];
    [self addBonntsView];
    kHMBlueToothManager.failureBlock = ^(NSString *value) {
        
    };
    kHMBlueToothManager.bluetoothConnectionDisconnect = ^(NSString *value) {
        self.navigationController.navigationBar.barTintColor = KK_MailColor;
        self.navigationItem.title = @"蓝牙连接断开";
        [PopupView showMessageStr:@"蓝牙连接断开"];
    };
}


- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"ConnectionStatus"] isEqualToString:@"连接成功"]) {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.48 green:0.69 blue:0.29 alpha:1.00];
        self.navigationItem.title = @"蓝牙连接成功";
    }else{
        self.navigationController.navigationBar.barTintColor = KK_MailColor;
        self.navigationItem.title = @"蓝牙连接断开";
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark 触发事件
- (void)clickStartDateEvent{
    KSDatePicker* picker = [[KSDatePicker alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 40, 300)];
    //配置中心，详情见KSDatePikcerApperance
    picker.appearance.radius = 5;
    picker.datePickerMode = UIDatePickerModeDate;
    //设置回调
    picker.appearance.resultCallBack = ^void(KSDatePicker* datePicker,NSDate* currentDate,KSDatePickerButtonType buttonType){
        if (buttonType == KSDatePickerButtonCommit) {
            NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            starDateDetailLabel.text = [formatter stringFromDate:currentDate];
            [starDateDetailLabel sizeToFit];
            starDateDetail = currentDate;
        }
    };
    //显示
    [picker show];
}
- (void)clickStartTimeEvent{
    KSDatePicker* picker = [[KSDatePicker alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 40, 300)];
    picker.appearance.radius = 5;
    picker.datePickerMode = UIDatePickerModeTime;
    picker.appearance.resultCallBack = ^void(KSDatePicker* datePicker,NSDate* currentDate,KSDatePickerButtonType buttonType){
        if (buttonType == KSDatePickerButtonCommit) {
            NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"HH:mm:00"];
            starTimeDetailLabel.text = [formatter stringFromDate:currentDate];
            [starTimeDetailLabel sizeToFit];
            
        }
    };
    [picker show];
}
- (void)clickStopDateEvent{
    KSDatePicker* picker = [[KSDatePicker alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 40, 300)];
    picker.appearance.radius = 5;
    picker.datePickerMode = UIDatePickerModeDate;
    picker.minimumDate = starDateDetail;
    picker.appearance.resultCallBack = ^void(KSDatePicker* datePicker,NSDate* currentDate,KSDatePickerButtonType buttonType){
        if (buttonType == KSDatePickerButtonCommit) {
            NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            stopDateDetailLabel.text = [formatter stringFromDate:currentDate];
            [stopDateDetailLabel sizeToFit];
        }
    };
    [picker show];
}
- (void)clickStopTimeEvent{
    KSDatePicker* picker = [[KSDatePicker alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 40, 300)];
    picker.appearance.radius = 5;
    picker.datePickerMode = UIDatePickerModeTime;
    picker.appearance.resultCallBack = ^void(KSDatePicker* datePicker,NSDate* currentDate,KSDatePickerButtonType buttonType){
        if (buttonType == KSDatePickerButtonCommit) {
            NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"HH:mm:00"];
            stopTimeDetailLabel.text = [formatter stringFromDate:currentDate];
            [stopTimeDetailLabel sizeToFit];
        }
    };
    [picker show];
}

- (void)clickReadButEvent{
    SearchEquipmentVC *searchVC = [SearchEquipmentVC new];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"ConnectionStatus"] isEqualToString:@"连接成功"]) {
        [self.dataSoucer removeAllObjects];
        h=1;
        SearchEquipmentModel *model = [SearchEquipmentModel new];
        model.num = @"序号";
        model.name = @"日期/时段";
        model.macID = @"埋深(米)";
        model.butTitle = @"水温(°C)";
        [self.dataSoucer addObject:model];
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd  HH:mm:ss"];
        NSDate *startDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@ 00:00:00",starDateDetailLabel.text]];
        NSDate *stopDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@ 00:00:00",stopDateDetailLabel.text]];
        NSTimeInterval halfDayInt = -60*60*16;
        NSDate *newdate = [[NSDate date] initWithTimeInterval:halfDayInt sinceDate:startDate];
        
        NSTimeInterval secondsInterval= [stopDate timeIntervalSinceDate:newdate];
        while (secondsInterval >= 7200) {
            for (int i=0; i<6; i++) {
                NSTimeInterval fourHours = 60*60*4;
                NSDate *senderDate = [[NSDate date] initWithTimeInterval:fourHours sinceDate:newdate];
                newdate = senderDate;
                
                NSDateFormatter * dateFormatter2 = [[NSDateFormatter alloc]init];
                [dateFormatter2 setDateFormat:@"yy,MM,dd,HH"];
                
                NSArray *array = [[dateFormatter2 stringFromDate:newdate] componentsSeparatedByString:@","]; //字符串按照【分隔成数组
                NSMutableString *str1 = [NSMutableString new];  //替换字符串
                for (NSString *str in array) {
                    NSString *newStr = [self inFrontOfTheFill:[[NSString alloc] initWithFormat:@"%1x",[str intValue]]];
                    str1 = [NSMutableString stringWithFormat:@"%@",[str1 stringByAppendingString:newStr]];
                }
                if (i==1) {
                    NSString *sendStr = [NSString stringWithFormat:@"6806000b03%@",str1];
                    NSString *checksum = [self getAddtion:[self hexToByteArr:sendStr]];
                    sendStr = [NSMutableString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@%@16",sendStr,checksum]];
                    NSData *data = [self stringToByte:sendStr];
                    [kHMBlueToothManager sendMsgWithSubPackage:data];
                    kHMBlueToothManager.dataBlock = ^(NSData *value) {
                        if (![self.dataSoucer isKindOfClass:[NSArray class]]) return ;
                        if ([strCopy isEqualToString:[NSString stringWithFormat:@"%@",value]]) {
                            return;
                        }
                        NSMutableString *str1 = [NSMutableString stringWithFormat:@"%@",value];
                        strCopy = [NSString stringWithFormat:@"%@",value];
                        //第一个参数是要删除的字符的索引，第二个是从此位开始要删除的位数
                        [str1 deleteCharactersInRange:NSMakeRange(0, 1)];
                        [str1 deleteCharactersInRange:NSMakeRange(str1.length-1, 1)];
                        //删除字符串中的空格
                        NSString *str4 = [str1 stringByReplacingOccurrencesOfString:@" " withString:@""];
                        NSString *str2 = [str4 substringToIndex:2];
                        NSString *str3 = [str4 substringFromIndex:str4.length-2];
                        
                        
                        if ([str2 isEqualToString:@"68"] && [str3 isEqualToString:@"16"]) {
                            str6 = str4;
                        }else if ([str2 isEqualToString:@"68"]){
                            str6 = str4;
                        }else if (![str3 isEqualToString:@"16"]){
                            str6 = [NSString stringWithFormat:@"%@%@",str6,str4];
                        }else{
                            str6 = [NSString stringWithFormat:@"%@%@",str6,str4];
                            NSLog(@"最后一行%@",str6);
                            if (![[str6 substringToIndex:6] isEqualToString:@"683600"] ) {
                                return ;
                            }
                            
                            NSMutableString *str7 = [NSMutableString stringWithFormat:@"%@",str6];
                            if (str7.length<110) {
                                return;
                            }
                            NSString *oneDayStr = [NSString new];
                            [str7 deleteCharactersInRange:NSMakeRange(0, 10)];
                            {
                                SearchEquipmentModel *model1 = [SearchEquipmentModel new];
                                model1.num = [NSString stringWithFormat:@"%d",h];
                                oneDayStr = [NSString stringWithFormat:@"20%@-%@-%@ %@:00:00",[NSString stringWithFormat:@"%lu",strtoul([[str7 substringToIndex:2] UTF8String],0,16)],[NSString stringWithFormat:@"%lu",strtoul([[str7 substringWithRange:NSMakeRange(2, 2)] UTF8String],0,16)],[NSString stringWithFormat:@"%lu",strtoul([[str7 substringWithRange:NSMakeRange(4, 2)] UTF8String],0,16)],[NSString stringWithFormat:@"%lu",strtoul([[str7 substringWithRange:NSMakeRange(6, 2)] UTF8String],0,16)]];
                                NSDate *date111 = [dateFormatter dateFromString:oneDayStr];
                                model1.name = [[NSString stringWithFormat:@"%@",[[NSDate date] initWithTimeInterval:fourHours*1 sinceDate:date111]] substringToIndex:19];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                NSData *data = [self stringToByte:[str7 substringToIndex:8]];
                                float y = *(float*)data.bytes;
                                model1.macID = [NSString stringWithFormat:@"%.1f",y];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                NSData *data1 = [self stringToByte:[str7 substringToIndex:8]];
                                float y1 = *(float*)data1.bytes;
                                model1.butTitle = [NSString stringWithFormat:@"%.1f",y1];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                [self.dataSoucer addObject:model1];
                                h++;
                            }
                            
                            {
                                NSDate *date111 = [dateFormatter dateFromString:oneDayStr];
                                SearchEquipmentModel *model1 = [SearchEquipmentModel new];
                                model1.num = [NSString stringWithFormat:@"%d",h];
                                model1.name = [[NSString stringWithFormat:@"%@",[[NSDate date] initWithTimeInterval:fourHours*2 sinceDate:date111]] substringToIndex:19] ;
                                NSData *data = [self stringToByte:[str7 substringToIndex:8]];
                                float y = *(float*)data.bytes;
                                model1.macID = [NSString stringWithFormat:@"%.1f",y];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                NSData *data1 = [self stringToByte:[str7 substringToIndex:8]];
                                float y1 = *(float*)data1.bytes;
                                model1.butTitle = [NSString stringWithFormat:@"%.1f",y1];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                [self.dataSoucer addObject:model1];
                                h++;
                            }
                            
                            {
                                NSDate *date111 = [dateFormatter dateFromString:oneDayStr];
                                SearchEquipmentModel *model1 = [SearchEquipmentModel new];
                                model1.num = [NSString stringWithFormat:@"%d",h];
                                
                                model1.name = [[NSString stringWithFormat:@"%@",[[NSDate date] initWithTimeInterval:fourHours*3 sinceDate:date111]] substringToIndex:19];
                                NSData *data = [self stringToByte:[str7 substringToIndex:8]];
                                float y = *(float*)data.bytes;
                                model1.macID = [NSString stringWithFormat:@"%.1f",y];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                NSData *data1 = [self stringToByte:[str7 substringToIndex:8]];
                                float y1 = *(float*)data1.bytes;
                                model1.butTitle = [NSString stringWithFormat:@"%.1f",y1];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                [self.dataSoucer addObject:model1];
                                h++;
                            }
                            
                            {
                                NSDate *date111 = [dateFormatter dateFromString:oneDayStr];
                                SearchEquipmentModel *model1 = [SearchEquipmentModel new];
                                model1.num = [NSString stringWithFormat:@"%d",h];
                                
                                model1.name = [[NSString stringWithFormat:@"%@",[[NSDate date] initWithTimeInterval:fourHours*4 sinceDate:date111]] substringToIndex:19];
                                NSData *data = [self stringToByte:[str7 substringToIndex:8]];
                                float y = *(float*)data.bytes;
                                model1.macID = [NSString stringWithFormat:@"%.1f",y];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                NSData *data1 = [self stringToByte:[str7 substringToIndex:8]];
                                float y1 = *(float*)data1.bytes;
                                model1.butTitle = [NSString stringWithFormat:@"%.1f",y1];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                [self.dataSoucer addObject:model1];
                                h++;
                            }
                            
                            {
                                NSDate *date111 = [dateFormatter dateFromString:oneDayStr];
                                SearchEquipmentModel *model1 = [SearchEquipmentModel new];
                                model1.num = [NSString stringWithFormat:@"%d",h];
                                model1.name = [[NSString stringWithFormat:@"%@",[[NSDate date] initWithTimeInterval:fourHours*5 sinceDate:date111]] substringToIndex:19];
                                NSData *data = [self stringToByte:[str7 substringToIndex:8]];
                                float y = *(float*)data.bytes;
                                model1.macID = [NSString stringWithFormat:@"%.1f",y];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                NSData *data1 = [self stringToByte:[str7 substringToIndex:8]];
                                float y1 = *(float*)data1.bytes;
                                model1.butTitle = [NSString stringWithFormat:@"%.1f",y1];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                [self.dataSoucer addObject:model1];
                                h++;
                            }
                            
                            {
                                NSDate *date111 = [dateFormatter dateFromString:oneDayStr];
                                SearchEquipmentModel *model1 = [SearchEquipmentModel new];
                                model1.num = [NSString stringWithFormat:@"%d",h];
                                
                                model1.name = [[NSString stringWithFormat:@"%@",[[NSDate date] initWithTimeInterval:fourHours*6 sinceDate:date111]] substringToIndex:19];
                                NSData *data = [self stringToByte:[str7 substringToIndex:8]];
                                float y = *(float*)data.bytes;
                                model1.macID = [NSString stringWithFormat:@"%.1f",y];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                NSData *data1 = [self stringToByte:[str7 substringToIndex:8]];
                                float y1 = *(float*)data1.bytes;
                                model1.butTitle = [NSString stringWithFormat:@"%.1f",y1];
                                [str7 deleteCharactersInRange:NSMakeRange(0, 8)];
                                [self.dataSoucer addObject:model1];
                                h++;
                            }
                            
                        }
                        [self.tableV reloadData];
                    };
                }
                
            }
            
            secondsInterval = secondsInterval - 86400;
        }
    }else{
        [self.navigationController pushViewController:searchVC animated:YES];
        [PopupView showMessageStr:@"请先连接蓝牙设备!"];
    }
    
}


#pragma mark - UITableViewDeletate 代理分组
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSoucer.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    EssentialParameterTableViewCell *cell = [EssentialParameterTableViewCell cellWithtableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setModel:self.dataSoucer[indexPath.row]];
    if (indexPath.row == 0) {
        cell.orderNumberLabel.textColor = KK_MailColor;
        cell.equipmentNameLabel.textColor = KK_MailColor;
        cell.macIDLabel.textColor = KK_MailColor;
        cell.connectBut.textColor = KK_MailColor;
        cell.orderNumberLabel.font = [UIFont systemFontOfSize:17];
        cell.equipmentNameLabel.font = [UIFont systemFontOfSize:17];
        cell.macIDLabel.font = [UIFont systemFontOfSize:17];
        cell.connectBut.font = [UIFont systemFontOfSize:17];
    }else{
        cell.orderNumberLabel.textColor = [UIColor blackColor];
        cell.equipmentNameLabel.textColor = [UIColor blackColor];
        cell.macIDLabel.textColor = [UIColor blackColor];
        cell.connectBut.textColor = [UIColor blackColor];
    }
    return cell;
}


#pragma mark 转换工具
//获取当地时间
- (NSString *)getCurrentDate {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

//获取当前的时间
-(NSString*)getCurrentTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:00"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
}
-(NSData*)stringToByte:(NSString*)string
{
    NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"%lu",(unsigned long)[hexString length]);
    if ([hexString length]%2!=0) {
        return nil;
    }
    Byte tempbyt[1]={0};
    NSMutableData* bytes=[NSMutableData data];
    for(int i=0;i<[hexString length];i++)
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            return nil;
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char2 >= 'A' && hex_char2 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            return nil;
        
        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里
        [bytes appendBytes:tempbyt length:1];
    }
    return bytes;
}



-(NSString *)stringFromHexString:(NSString *)hexString { //
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    //    NSLog(@"------字符串------%@",unicodeString);
    return unicodeString;
}
//把 byte数组转成 Int类型的数据
-(int) lBytesToInt:(NSString *)string
{
    NSString *str1 = [NSString stringWithFormat:@"%lu",strtoul([[string substringToIndex:2] UTF8String],0,16)];
    NSString *str2 = [NSString stringWithFormat:@"%lu",strtoul([[string substringWithRange:NSMakeRange(2, 2)] UTF8String],0,16)];
    NSString *str3 = [NSString stringWithFormat:@"%lu",strtoul([[string substringWithRange:NSMakeRange(4, 2)] UTF8String],0,16)];
    
    int  temp1 = [str1 intValue];
    int  temp2 = [str2 intValue];
    int  temp3 = [str3 intValue];
    Byte byte1[] = {temp1,temp2,temp3};
    
    int height = 0;
    NSData * testData =[NSData dataWithBytes:byte1 length:4];
    for (int i = 0; i < [testData length]; i++)
    {
        if (byte1[[testData length]-i] >= 0)
        {
            height = height + byte1[[testData length]-i];
        } else
        {
            height = height + 256 + byte1[[testData length]-i];
        }
        height = height * 256;
    }
    if (byte1[0] >= 0)
    {
        height = height + byte1[0];
    } else {
        height = height + 256 + byte1[0];
    }
    return height;
}


- (int)hextoint:(NSString *)string
{
    NSString *str1 = [NSString stringWithFormat:@"%lu",strtoul([[string substringToIndex:2] UTF8String],0,16)];
    NSString *str2 = [NSString stringWithFormat:@"%lu",strtoul([[string substringWithRange:NSMakeRange(2, 2)] UTF8String],0,16)];
    NSString *str3 = [NSString stringWithFormat:@"%lu",strtoul([[string substringWithRange:NSMakeRange(4, 2)] UTF8String],0,16)];
    NSString *str4 = [NSString stringWithFormat:@"%lu",strtoul([[string substringWithRange:NSMakeRange(6, 2)] UTF8String],0,16)];
    
    int  temp1 = [str1 intValue];
    int  temp2 = [str2 intValue];
    int  temp3 = [str3 intValue];
    int  temp4 = [str4 intValue];
    Byte dataVal[] = {temp1,temp2,temp3,temp4};
    int reVal = -1;
    
    
    reVal = (int)dataVal[3] << 24;
    
    reVal += (int)dataVal[2] << 16;
    
    reVal += (int)dataVal[1] << 8;
    
    reVal += (int)dataVal[0];
    return reVal;
}

//普通字符串转换为十六进制的。
- (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}





//测试
- (NSMutableArray *)hexToByteArr:(NSString *)str{
    int hexlen = (int)str.length;
    NSMutableArray *array = [NSMutableArray new];
    Byte result[str.length/2];
    if ([self isOdd:hexlen] == 1) {
        ++hexlen;
        str = [NSString stringWithFormat:@"0%@",str];
    }else{
        
    }
    
    int j = 0;
    for (int i = 0; i<hexlen; i+=2) {
        NSString *bstr = [NSString stringWithFormat:@"%lu",strtoul([[str substringWithRange:NSMakeRange(i, 2)] UTF8String],0,16)];
        if ([bstr intValue] >128) {
            bstr = [NSString stringWithFormat:@"%d",[bstr intValue]-256];
        }else if ([bstr intValue]<-128){
            bstr = [NSString stringWithFormat:@"%d",256+[bstr intValue]];
        }
        [array addObject:bstr];
        j++;
    }
    //    NSLog(@"%@",array);
    return array;
}

- (NSString *)getAddtion:(NSMutableArray *)byte{
    int len = byte.count;
    int num = 0;
    for (int i = 0; i<len; i++) {
        num += [byte[i] intValue];
        NSLog(@"基数：%@",[NSString stringWithFormat:@"%d",[byte[i] intValue]]);
        if (num>128) {
            num = num-256;
        }else if (num<-128){
            num = 256+num;
        }
        NSLog(@"求和：%@",[NSString stringWithFormat:@"%d",num]);
    }
    
    if (num<10 && num>0) {
        NSLog(@"--%@",[NSString stringWithFormat:@"0%@",[self ToHex:[[NSString stringWithFormat:@"0%d",num] intValue]]]);
        return [NSString stringWithFormat:@"0%@",[self ToHex:[[NSString stringWithFormat:@"0%d",num] intValue]]];
    }else if (num<0){
        num = 256+num;
        NSLog(@"==%@",[self ToHex:[[NSString stringWithFormat:@"%d",num] intValue]]);
        return [self ToHex:[[NSString stringWithFormat:@"%d",num] intValue]];
    }else{
        NSLog(@"++%@",[self ToHex:[[NSString stringWithFormat:@"%d",num] intValue]]);
        return [self ToHex:[[NSString stringWithFormat:@"%d",num] intValue]];
    }
}

- (int)isOdd:(int )num{
    return num & 1;
}


-(NSString *)ToHex:(long long int)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    long long int ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:nLetterValue=[[NSString alloc]initWithFormat:@"%lli",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
        
    }
    return str;
}

//判断数字是否小于10 如果小于前面补0
- (NSString *)inFrontOfTheFill:(NSString *)str{
    if (str.length == 1) {
        str = [NSString stringWithFormat:@"0%@",str];
    }
    return str;
}

#pragma mark 视图布局
- (void)addTableView{
    self.tableV = [UITableView new];
    self.tableV.size = CGSizeMake(kScreenWidth, (kScreenHeight-108)/5*4);
    self.tableV.left = 0;
    self.tableV.top = 0;
    self.tableV.dataSource = self;
    self.tableV.delegate = self;
    self.tableV.tableFooterView  = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableV registerClass:[EssentialParameterTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:self.tableV];
    
    
}

- (void)addBonntsView{
    UIView *baseView = [UIView new];
    baseView.size = CGSizeMake(kScreenWidth, (kScreenHeight-108)/5);
    baseView.top = self.tableV.bottom;
    baseView.left = 0;
    baseView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.00];
    [self.view addSubview:baseView];
    
    UILabel *startDateLabel = [UILabel new];
    startDateLabel.text = @"起始日期 ";
    [startDateLabel sizeToFit];
    startDateLabel.left = 20;
    startDateLabel.top = 8;
    [baseView addSubview:startDateLabel];
    starDateDetailLabel = [UILabel new];
    starDateDetailLabel.text = [self getCurrentDate];
    [starDateDetailLabel sizeToFit];
    starDateDetailLabel.left = startDateLabel.right;
    starDateDetailLabel.top = startDateLabel.top;
    starDateDetailLabel.layer.borderWidth = 0.2;
    starDateDetailLabel.layer.borderColor = [UIColor grayColor].CGColor;
    starDateDetailLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *starDataTGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickStartDateEvent)];
    [starDateDetailLabel addGestureRecognizer:starDataTGR];
    [baseView addSubview:starDateDetailLabel];
    
    UILabel *stopDateLabel = [UILabel new];
    stopDateLabel.text = @"结束日期 ";
    [stopDateLabel sizeToFit];
    stopDateLabel.left = startDateLabel.left;
    stopDateLabel.top = startDateLabel.bottom +10;
    [baseView addSubview:stopDateLabel];
    stopDateDetailLabel = [UILabel new];
    stopDateDetailLabel.text = [self getCurrentDate];
    [stopDateDetailLabel sizeToFit];
    stopDateDetailLabel.left = stopDateLabel.right;
    stopDateDetailLabel.top = stopDateLabel.top;
    stopDateDetailLabel.layer.borderWidth = 0.2;
    stopDateDetailLabel.layer.borderColor = [UIColor grayColor].CGColor;
    stopDateDetailLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *stopDataTGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickStopDateEvent)];
    [stopDateDetailLabel addGestureRecognizer:stopDataTGR];
    [baseView addSubview:stopDateDetailLabel];
    
    UILabel *startTimeLabel = [UILabel new];
    startTimeLabel.text = @"起始时间 ";
    [startTimeLabel sizeToFit];
    startTimeLabel.left = starDateDetailLabel.right+20;
    startTimeLabel.top = startDateLabel.top;
    [baseView addSubview:startTimeLabel];
    starTimeDetailLabel = [UILabel new];
    starTimeDetailLabel.text = @"00:00:00";
    [starTimeDetailLabel sizeToFit];
    starTimeDetailLabel.left = startTimeLabel.right;
    starTimeDetailLabel.top = startTimeLabel.top;
    starTimeDetailLabel.layer.borderWidth = 0.2;
    starTimeDetailLabel.layer.borderColor = [UIColor grayColor].CGColor;
    starTimeDetailLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *starTimeTGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickStartTimeEvent)];
    [starTimeDetailLabel addGestureRecognizer:starTimeTGR];
    [baseView addSubview:starTimeDetailLabel];
    
    UILabel *stopTimeLabel = [UILabel new];
    stopTimeLabel.text = @"结束时间 ";
    [stopTimeLabel sizeToFit];
    stopTimeLabel.left = startTimeLabel.left;
    stopTimeLabel.top = stopDateLabel.top;
    [baseView addSubview:stopTimeLabel];
    stopTimeDetailLabel = [UILabel new];
    stopTimeDetailLabel.text = @"00:00:00";
    [stopTimeDetailLabel sizeToFit];
    stopTimeDetailLabel.left = stopTimeLabel.right;
    stopTimeDetailLabel.top = stopTimeLabel.top;
    stopTimeDetailLabel.layer.borderWidth = 0.2;
    stopTimeDetailLabel.layer.borderColor = [UIColor grayColor].CGColor;
    stopTimeDetailLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *stopTimeTGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickStopTimeEvent)];
    [stopTimeDetailLabel addGestureRecognizer:stopTimeTGR];
    [baseView addSubview:stopTimeDetailLabel];
    
    UIButton *readBut = [UIButton new];
    readBut.size = CGSizeMake(100, 34);
    readBut.centerX = baseView.centerX;
    readBut.top = stopDateLabel.bottom + 10;
    readBut.backgroundColor = KK_MailColor;
    [readBut setTitle:@"读取" forState:(UIControlStateNormal)];
    [readBut setTintColor:[UIColor whiteColor]];
    readBut.layer.cornerRadius = 6;
    [readBut addTarget:self action:@selector(clickReadButEvent) forControlEvents:(UIControlEventTouchUpInside)];
    [baseView addSubview:readBut];

}

@end
